<template>
    <div class="preview">
        <a-button type="primary" @click="getFilesData('preview')" :disabled="isButton" :loading="loading">预览</a-button>
        <a-modal :visible="visible" width="800px" :footer="null" @cancel="cancel">
            <!-- <iframe :src="previewUrl" width="100%" height="600" class="w-full h-[600px]"></iframe> -->
            <a-spin :spinning="preLoading" style="width: 100%;min-height: 40vh;">
                <div ref="file" class="file"></div>
            </a-spin>
        </a-modal>
    </div>
</template>

<script>
import qs from "qs";
// import { renderAsync } from 'docx-preview';
import JSZip from 'jszip';

export default {
    name: 'Preview',
    props: {
        isButton: {
            type: Boolean,
        },
        formData: {
            type: Object,
        },
        type: {
            type: [String, Number]
        },
        formType: {
            type: [String, Number]
        }
    },
    data() {
        return {
            previewUrl: '',
            fileType: '',// docx
            visible: false,
            loading: false,
            preLoading: true,
        }
    },
    methods: {
        getFilesData() {
            this.previewUrl = '';
            return
            window.JSZip = JSZip;
            let params = {
                type: this.type,
            };
            let questUrl;
            if (params.type == 'week') {
                questUrl = this.$excelExportWeek;
            } else if (params.type == 'loop') {
                questUrl = this.$excelClosedLoopExport;
            } else {
                questUrl = this.$getexportzlfxmonth;
            }
            if (this.formType == 'modal') {
                questUrl = this.$monthlyStatement
            }
            let formData = this.formData;
            if (params.type == 'week') {
                params["company"] = formData["company"];
                params["startTime"] = formData["date"][0];
                params["endTime"] = formData["date"][1];
            } else if (params.type == 'loop') {
                params["company"] = formData["company"];
                params["startTime"] = formData["date"][0];
                params["endTime"] = formData["date"][1];
            } else {
                params["code"] = formData["company"];
                params["date"] = formData["date"];
            }
            let str = qs.stringify(params);
            // this.previewUrl = `${questUrl}?${str}`;
            this.loading = true;
            this.visible = true;
            this.preLoading = true;
            this.getAxios(questUrl, params, {}, { responseType: "blob" })
                .then(async (res) => {
                    try {
                        const blob = new Blob([res], {
                            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        });
                        const arrayBuffer = await this.blobToArrayBuffer(blob);
                        await renderAsync(arrayBuffer, this.$refs.file, null,        // 样式自定义（可选）
                            {
                                ignoreWidth: false,  // 忽略文档原始宽度
                                ignoreHeight: false, // 忽略文档原始高度
                                debug: false        // 关闭调试模式
                            });
                    } catch (err) {
                    }

                    // const blob = new Blob([res], { type: 'application/msword' });
                    // this.previewUrl = URL.createObjectURL(blob);
                    // console.log('预览URL:', this.previewUrl);
                    // if (res) {
                    //     const blob = new Blob([res], {
                    //         type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8",
                    //     }); // 构造一个blob对象来处理数据，并设置文件类型
                    //     // 兼容不同浏览器的URL对象
                    //     // const url = window.URL || window.webkitURL || window.moxURL;
                    //     console.log('URL.createObjectURL(res)==', URL.createObjectURL(res));
                    //     this.previewUrl = URL.createObjectURL(res);
                    //     console.log('this.previewUrl==', this.previewUrl);
                    //     this.visible = true;
                    // }
                }).catch(() => {
                    this.visible = false;
                })
                .finally(() => {
                    this.loading = false;
                    this.preLoading = false;
                });
        },
        blobToArrayBuffer(blob) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsArrayBuffer(blob); // 读取Blob为ArrayBuffer
            });
        },
        cancel() {
            this.visible = false;
            this.loading = false;
            this.preLoading = false;
            this.previewUrl = '';
        },
        changeFormat() {

        }
    },
    mounted() {
    },
    watch: {
        previewUrl(nVal, oVal) {
            if (!nVal) {
                this.previewUrl = '';
            }
        }
    }
}
</script>

<style lang="less" scoped>
::v-deep {
    .ant-modal-body {
        height: 100%;
        max-height: 80vh;
        min-height: 30vh;
        overflow-y: auto;
        overflow-x: hidden;
    }

    .docx-wrapper {
        padding: 0px;
    }

    .file {
        background-color: #ffffff;
    }
}
</style>